package com.ysy.strategy.impl;

import com.ysy.config.MinioProperties;
import com.ysy.dto.DelFileReqDTO;
import com.ysy.persimmons.common.response.Response;
import com.ysy.persimmons.common.util.StringUtils;
import com.ysy.strategy.FileUploadStrategy;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;


@Component
public class MinioUploadStrategy implements FileUploadStrategy {

    private static final Logger log = LoggerFactory.getLogger(MinioUploadStrategy.class);

    @Resource
    private  MinioClient minioClient;

    @Resource
    private MinioProperties minioProperties;

    @Override
    public Response<?> upload(MultipartFile file, String bucketName, String objectName)  {

        // 判断文件是否为空
        if (file == null || file.getSize() == 0) {
            log.error("文件是否为空");
            throw new RuntimeException("文件大小不能为空");
        }

        try {
            // 文件的原始名称
            String originalFileName = file.getOriginalFilename();
            // 文件的 Content-Type
            String contentType = file.getContentType();
            // 生成存储对象的名称（将 UUID 字符串中的 - 替换成空字符串）
            String key = UUID.randomUUID().toString().replace("-", "");
            // 获取文件的后缀
            String suffix = null;
            if (originalFileName != null) {
                suffix = originalFileName.substring(originalFileName.lastIndexOf("."));
            } else {
                log.info(" 上传文件至 Minio 失败:文件名称为空 ");
                throw new RuntimeException("文件名称为空");
            }

            // 拼接上文件后缀，即为要存储的文件名
            objectName = String.format("%s%s", key, suffix);

            log.info("==> 开始上传文件至 Minio, ObjectName: {}", objectName);

            if (StringUtils.isEmpty(bucketName)) {
                bucketName = minioProperties.getBucket();
            }

            // 上传文件至 Minio
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)//
                    .object(objectName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(contentType)
                    .build());

            // 返回文件的访问链接
            String url = String.format("%s/%s/%s", minioProperties.getEndpoint(), bucketName, objectName);
            log.info("==> 上传文件至 Minio 成功，访问路径: {}", url);

            return Response.success(url);
        } catch (Exception e) {
            log.error(" 上传文件至 Minio 失败: ",e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public Response<?> delete(DelFileReqDTO delFileReqDTO) {
        try {
            minioClient.removeObject(RemoveObjectArgs.builder()
                    .bucket(minioProperties.getBucket())
                    .object(delFileReqDTO.getFileName())
                    .build());
            return Response.success(true);
        } catch (Exception e) {
            log.error(" Minio 删除文件失败: ",e);
            return Response.fail(false);
        }
    }
}
